﻿<div id="MonitorTreeDiv" class="MonitorFlexBox-V MonitorFlex-1">
    <div class="MenuDiv">
        <input type="text" class="ConditionInput" placeholder="车牌号、SIM卡号、车辆编号"/>
        <input type="button" class="Refresh" value="刷新" onclick="RefreshVehiclesDeparts()" />
    </div>
    <div id="MonitorTreeContentWrap" class="MonitorFlexBox-V MonitorFlex-1">
        <div id="MonitorTreeWaitingDiv">
            @Html.Partial("~/Views/MonitorCenter/Loading.cshtml")
        </div>
        <div id="MonitorTreeErrorDiv" style="margin-left:-60px">
            <span id="MonitorTreeErrorCode"></span>
            <input type="button" value="重试" onclick="RefreshVehiclesDeparts()"/>
        </div>
        <div id="MonitorTreeContentDiv" class="MonitorFlex-1">
            <ul id="MonitorTree" class="ztree"></ul>
        </div>
    </div>

    <div id="rMenu">
	    <ul>
		    <li id="VehicleInfo" rel="">目标信息</li>
		    <li id="VehicleHistory" rel="">轨迹回放</li>
		    @*<li>历史警情</li>
		    <li>里程统计</li>*@
		    <li id="VehicleTrack" rel="">目标跟踪</li>
@*            <li>电子围栏</li>
            <li>超速设置</li>
            <li>信息发送</li>*@
            <li id="StationLocation" rel="">基站定位</li>
	    </ul>
    </div>
</div>
<script type="text/javascript">
    var vehiclesdeparts = [];//所有单位车辆
    var vehicles = [];//所有车辆，用于查询
    var vehiclesGpsInfo = {};//所有车辆的基础信息以及之后更新的最新gps信息
    var vehiclesdeparts_loadcomplete = false;
    var vehiclesbasicinfo_loadcomplete = false;
    //树形参数
    var setting = {
        check: {
            enable: true,
            autoCheckTrigger: false
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onRightClick: OnRightClick,
            onCheck: OnNodeCheck,
            onDblClick: OnNodeDblClick
        }
    };
    $(document).ready(function () {
        //$("#MonitorTreeContentDiv").height($("#MonitorTreeDiv").height() - $("#MonitorTreeConditionDiv").height())
        //$("#MonitorTreeWaitingDiv").height($("#MonitorTreeContentDiv").height());
        $("#MonitorTreeWaitingDiv").show();
        $("#MonitorTreeContentDiv").hide();
        $("#MonitorTreeErrorDiv").hide();

        GetVehiclesDeparts();
        GetVehiclesBasicInfo();
        RefreshTimeout();

        BindRightMenuEvent();
    })
    //定时刷新
    function RefreshTimeout() {
        UpdateOnCheck();
        setTimeout(RefreshTimeout, 10000);
    }
    //刷新单位车辆信息
    function RefreshVehiclesDeparts() {
        $("#MonitorTreeWaitingDiv").show();
        $("#MonitorTreeContentDiv").hide();
        $("#MonitorTreeErrorDiv").hide();

        vehiclesbasicinfo_loadcomplete = false;
        vehiclesdeparts_loadcomplete = false;
        GetGpsData(null);

        GetVehiclesDeparts();
        GetVehiclesBasicInfo();
    }
    //获取车辆基础信息
    function GetVehiclesBasicInfo() {
        $.ajax({
            type: "get",
            url: "/MonitorCenter/GetVehiclesBasicInfo",
            dataType: "json",
            success: function (ret) {
                vehiclesbasicinfo_loadcomplete = true;
                if (vehiclesdeparts_loadcomplete) {
                    $("#MonitorTreeWaitingDiv").hide();
                    $("#MonitorTreeContentDiv").show();
                }
                //赋值基础信息
                for (var i = 0; i < ret.length; i++) {
                    vehiclesGpsInfo[ret[i].sim] = ret[i];

                    //alert("ret.sim:" + ret[i].sim + "==ret.id:" + ret[i].id + "  " + vehiclesGpsInfo[ret[i].sim].id);
                }

            },
            error: function (XMLHttpRequest) {
               // alert(JSON.stringify(XMLHttpRequest));
                //GetVehiclesBasicInfo();
                $("#MonitorTreeWaitingDiv").hide();
                $("#MonitorTreeContentDiv").hide();
                $("#MonitorTreeErrorDiv").show();
                $("#MonitorTreeErrorCode").text("错误代码：" + XMLHttpRequest.status)
            }
        });
    }
    //获取单位车辆信息
    function GetVehiclesDeparts() {
        $.ajax({
            type: "get",
            url: "/MonitorCenter/GetVehicles",
            dataType: "json",
            success: function (ret) {
                vehiclesdeparts = [];
                vehiclesdeparts = ret;
                ExpandOneLevel(ret);
                //var rootNode = {
                //    id: "rootnode",
                //    name: "监控中心",
                //    open: true,
                //    checked: false,
                //    icon: "/Content/themes/zTreeStyle/img/diy/1_open.png"
                //}
                //for (var i = 0; i < ret.length; i++) {
                //    if (ret[i].pId == null || ret[i].pId == "") {
                //        ret[i].pId = "rootnode";
                //    }
                //}
                //ret.push(rootNode);
                $.fn.zTree.init($("#MonitorTree"), setting, ret);
                //筛选车辆
                vehicles = [];
                for (var i = 0; i < vehiclesdeparts.length; i++) {
                    if (vehiclesdeparts[i].id.substring(0, 4) == "VEHI") {
                        vehicles.push(vehiclesdeparts[i]);
                    }
                }
                //自动完成查询
                $(".ConditionInput").autocomplete(vehicles, {
                    minChars: 0,
                    width: $("#MonitorTreeDiv").width(),
                    matchContains: true,
                    autoFill: false,
                    formatItem: function (row, i, max) {
                        return row.name + "," + row.sim;
                    },
                    formatMatch: function (row, i, max) {
                        return row.name + " " + row.id + " " + row.sim;
                    },
                    formatResult: function (row) {
                        return row.name;
                    }
                }).result(function (event, row, formatted) {
                    FocusAndCheckNode(row);
                });
                vehiclesdeparts_loadcomplete
                vehiclesdeparts_loadcomplete = true;
                if (vehiclesbasicinfo_loadcomplete) {
                    $("#MonitorTreeWaitingDiv").hide();
                    $("#MonitorTreeContentDiv").show();
                }
            },
            error: function (XMLHttpRequest) {
                //alert(JSON.stringify(XMLHttpRequest));
                //GetVehiclesDeparts();
                $("#MonitorTreeWaitingDiv").hide();
                $("#MonitorTreeContentDiv").hide();
                $("#MonitorTreeErrorDiv").show();
                $("#MonitorTreeErrorCode").text("错误代码：" + XMLHttpRequest.status)
            }
        });
    }
    //获得节点焦点并选择焦点
    function FocusAndCheckNode(row) {
        var ztree = $.fn.zTree.getZTreeObj("MonitorTree");
        var node = ztree.getNodesByParam("id", row.id, null)[0];
        ExpandParent(node);
        ztree.expandNode(node, true, false, true);
        if (node.checked == false) {
            ztree.checkNode(node, true, true, true);
        }
        ztree.selectNode(node);
        SelectRowAndFocus(node.sim);
    }
    //展开父节点
    function ExpandParent(node) {
        var ztree = $.fn.zTree.getZTreeObj("MonitorTree");
        var parentNode = node.getParentNode();
        if (parentNode != null) {
            ztree.expandNode(parentNode, true, false, true);
            ExpandParent(parentNode);
        }
    }
    //展开一级
    function ExpandOneLevel(rightArray) {
        for (var i = 0; i < rightArray.length; i++) {
            if (rightArray[i].pId == null) {
                rightArray[i].open = true;
            }
        }
    }

    //右键点击
    function OnRightClick(event, treeId, treeNode) {
        if (treeNode != null) {
            //不为空并且为车辆节点
            var ztree = $.fn.zTree.getZTreeObj("MonitorTree");
            ztree.selectNode(treeNode);
            ShowRMenu(event.clientX, event.clientY, treeNode);
        }

    }

    //显示右键菜单
    function ShowRMenu(x, y, node) {
        $("#rMenu").css({ "top": y + "px", "left": x + "px", "visibility": "visible" });
        //车辆信息冒泡窗口
        InitRightMenu(x, y, node);
        //点击空白处
        $("body").bind("mousedown", HideRMenu);

    }
    //隐藏右键菜单
    function HideRMenu(event) {
        if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
            $("#rMenu").css({ "visibility": "hidden" });
        }
    }

    //右键菜单事件绑定
    function BindRightMenuEvent() {
        //目标信息
        $("#VehicleInfo").click(function () {
            artDialogForm($(this).attr("rel"), "目标信息", "", 700, 360);
            $("#rMenu").css({ "visibility": "hidden" });
        });
        //历史轨迹
        $("#VehicleHistory").click(function () {
            window.open($(this).attr("rel"));
            $("#rMenu").css({ "visibility": "hidden" });
        });
        //车辆跟踪
        $("#VehicleTrack").click(function () {
            window.open($(this).attr("rel"));
            $("#rMenu").css({ "visibility": "hidden" });
        });
        //基站定位
        $("#StationLocation").click(function () {
            $.ajax({
                type: "post",
                url: $(this).attr("rel"),
                success: function (ret) {
                    artDialogAlert("基站定位请求已发送", +(ret.ret == true ? "成功" : "失败"));
                },
                error: function (XMLHttpRequest) {

                }
            });
            $("#rMenu").css({ "visibility": "hidden" });
        });
    }

    //右键菜单初始化
    function InitRightMenu(x, y, node) {

        if (node && node.id.substring(0, 4) == "VEHI") {
            $("#VehicleInfo").show();
            $("#VehicleHistory").show();
            $("#VehicleTrack").show();
            //目标信息
            $("#VehicleInfo").attr("rel", "/MonitorCenter/GetVehicleInfo?vehicleNum=" + node.id);
            //历史轨迹
            $("#VehicleHistory").attr("rel", "/MonitorCenter/VehicleHistory?vehicleNum=" + node.id);
            //车辆跟踪
            $("#VehicleTrack").attr("rel", "/MonitorCenter/VehicleTrack?vehicleNum=" + node.id);
            if (node.others == "5") {//终端类型：人员
                $("#StationLocation").show();
            }
            else {
                $("#StationLocation").hide();
            }
            //基站定位
            $("#StationLocation").attr("rel", "/MonitorCenter/StationLocation?sim=" + node.sim);
        }
        else {
            $("#VehicleInfo").hide();
            $("#VehicleHistory").hide();
            $("#VehicleTrack").hide();
            $("#StationLocation").show();
            //基站定位
            $("#StationLocation").attr("rel", "/MonitorCenter/DepartStationLocation?departId=" + node.id);
        }
    }

    //更新选中节点
    function UpdateOnCheck() {
        if (vehiclesbasicinfo_loadcomplete && vehiclesdeparts_loadcomplete) {
            var ztree = $.fn.zTree.getZTreeObj("MonitorTree");
            var nodes = ztree.getCheckedNodes(true);
            var sims = [];
            if (nodes != null && nodes.length != 0) {
                for (var i = 0; i < nodes.length; i++) {
                    if (nodes[i].id.substring(0, 4) == "VEHI") {
                        sims.push(nodes[i].sim);
                    }
                }
                GetGpsData(sims);
            }
        }
    }
    //双击节点
    function OnNodeDblClick(event, treeId, treeNode) {
        if (vehiclesbasicinfo_loadcomplete && vehiclesdeparts_loadcomplete) {
            if (treeNode.id.substring(0, 4) == "VEHI") {
                var ztree = $.fn.zTree.getZTreeObj(treeId);
                if (treeNode.checked == false) {
                    ztree.checkNode(treeNode, true, true, true);
                }
                ztree.selectNode(treeNode);
                SelectRowAndFocus(treeNode.sim);
            }
        }
    }
    //选中节点
    function OnNodeCheck(event, treeId, treeNode) {
        $("#MonitorMapWaitingDiv").show();
        setTimeout(function () {
            if (vehiclesbasicinfo_loadcomplete && vehiclesdeparts_loadcomplete) {
                var ztree = $.fn.zTree.getZTreeObj("MonitorTree");
                var nodes = ztree.getChangeCheckedNodes();//获取全部变化的节点
                var sims = [];
                if (nodes != null && nodes.length != 0) {
                    if (nodes.length < 20) {
                        for (var i = 0; i < nodes.length; i++) {
                            if (nodes[i].id.substring(0, 4) == "VEHI") {
                                if (nodes[i].checkedOld == true) {
                                    DeleteVehicleFromDataGrid(nodes[i].sim);
                                }
                                else {
                                    if (vehiclesGpsInfo[nodes[i].sim].time == null || vehiclesGpsInfo[nodes[i].sim].time == "") {
                                        //没有最新的gps信息
                                        sims.push(nodes[i].sim);
                                    }
                                    AddVehicleToDataGrid(nodes[i].sim);
                                }
                            }
                            nodes[i].checkedOld = nodes[i].checked;
                        }
                    }
                    else {
                        var tmpAddNodes = [];
                        var tmpDelNodes = [];
                        for (var i = 0; i < nodes.length; i++) {
                            if (nodes[i].id.substring(0, 4) == "VEHI") {
                                if (nodes[i].checkedOld == false) {
                                    if (vehiclesGpsInfo[nodes[i].sim].time == null || vehiclesGpsInfo[nodes[i].sim].time == "") {
                                        //没有最新的gps信息
                                        sims.push(nodes[i].sim);
                                    }
                                    tmpAddNodes.push(vehiclesGpsInfo[nodes[i].sim]);
                                }
                                else {
                                    tmpDelNodes.push(vehiclesGpsInfo[nodes[i].sim]);
                                }
                            }
                            nodes[i].checkedOld = nodes[i].checked;
                        }
                        ReloadTable(tmpAddNodes,tmpDelNodes);
                    }
                }
            }
            $("#MonitorMapWaitingDiv").hide();
        }, 100);
    }

    /*更新节点图标*/
    function UpdateNodeIcon(sim, time, acc) {
        var ztree = $.fn.zTree.getZTreeObj("MonitorTree");
        var node = ztree.getNodesByParam("sim", sim, null)[0];
        var url = "";
        if (GetTimeOffsetToNow(time) > 30) {//离线半个小时
            url = "/Content/themes/zTreeStyle/img/diy/car.png";
        }
        else {
            if (acc == "开") {
                url = "/Content/themes/zTreeStyle/img/diy/6.png";
            }
            else {
                url = "/Content/themes/zTreeStyle/img/diy/4.png";
            }
        }
        if (node.icon != url) {
            node.icon = url;
            ztree.updateNode(node);
        }
    }

    /*获取时间间隔(分)*/
    function GetTimeOffsetToNow(time) {
        var sTime = new Date(time.replace(/\-/g, "/")); //开始时间
        var eTime = new Date();  //结束时间
        return parseInt(eTime.getTime() - sTime.getTime()) / 60000
    }
</script>
